/**
 * 字典工具函数
 */
import type { App } from 'vue';
import { useDictStore } from '@/store/modules/dict';
import { getDicts } from '@/api/system/dict/data';

export interface DictDataItem {
  label: string;
  value: string | number;
  dictType?: string;
  cssClass?: string;
  listClass?: string;
  isDefault?: string;
  status?: string;
  createTime?: string;
  remark?: string;
}

/**
 * 获取字典数据
 */
export function useDict(...args: string[]) {
  const res = ref<Record<string, DictDataItem[]>>({});
  return (() => {
    args.forEach((dictType) => {
      res.value[dictType] = [];
      const dicts = useDictStore().getDict(dictType);
      if (dicts) {
        res.value[dictType] = dicts;
      } else {
        getDicts(dictType).then((resp: any) => {
          res.value[dictType] = resp.data.map(
            (p: any) =>
              ({
                label: p.dictLabel,
                value: p.dictValue,
                elTagType: p.listClass,
                elTagClass: p.cssClass,
              }) as DictDataItem,
          );
          useDictStore().setDict({ key: dictType, value: res.value[dictType] });
        });
      }
    });
    return toRefs(res.value);
  })();
}

/**
 * 安装字典工具到 Vue 应用
 */
export function installDict(app: App) {
  app.config.globalProperties.useDict = useDict;
}

